﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Windows.Forms;
using AMM.Business;
using AMM.Business.Config;
using AMM.Forms.Business;
using AMM.Forms.Config;
using AMM.Forms.Finance;
using AMM.Forms.Produce;
using AMM.Forms.Project;
using AMM.Forms.Reports.ReportUserControls;
using AMM.Forms.Store;
using AMM.Properties;

namespace AMM.Forms {
    public partial class FrmMDIContainer : FrmRootBase {

        private ConfigurationProcessor _configProcessor;
        private int _alertCount;

        #region Public methods

        public void SetStatusProcessBar(int value) {
            this.tsPBar.Visible = true;
            this.tsPBar.Value = value;
            this.tssLabelInfomation.Text = (value / 100.00f * 100) + "%";
            if (this.tsPBar.Maximum == value) {
                this.tsPBar.Visible = false;
                this.tssLabelInfomation.Text = "准备";
            }
        }

        public void SetStatusInformation(string text) {
            this.tssLabelInfomation.Text = text;
        }

        #endregion

        public FrmMDIContainer() {
            this.InitializeComponent();
        }

        #region Private methods

        private Form CheckIfExists(Form frm) {
            Form resultFrm = this.MdiChildren.FirstOrDefault(x => x.GetType() == frm.GetType());
            if (resultFrm == null) { resultFrm = frm; }
            return resultFrm;
        }

        private FrmReport CheckIfExists(FrmReport frmReport) {
            List<FrmReport> frmList = this.MdiChildren.Where(x => x.GetType() == frmReport.GetType()).Cast<FrmReport>().ToList();
            FrmReport resultFrm = frmList.FirstOrDefault(x => x.FunctionCode == frmReport.FunctionCode);
            if (resultFrm == null) { resultFrm = frmReport; }
            return resultFrm;
        }

        private void SetAllMenuItemPermission() {
            PowerHelper powerHelper = new PowerHelper();
            Dictionary<string, int> powers = new UserProcessor().FetchUserAllMenuPermission(LoginUserId);

            Action<ToolStripMenuItem> action = null;
            action = menuItem => {
                for (int i = 0; i < menuItem.DropDownItems.Count; i++) {
                    ToolStripMenuItem item = menuItem.DropDownItems[i] as ToolStripMenuItem;
                    if (item == null) { continue; }
                    if (item.DropDownItems.Count > 0) {
                        action.Invoke(item);
                    }
                    else {
                        if (item.Name.StartsWith("AMM")) {
                            if (powers.Keys.Contains(item.Name)) {
                                if (!powerHelper.FetchPowers(powers[item.Name]).Contains(Powers.Browse)) {
                                    item.Enabled = false;
                                }
                            }
                            else {
                                item.Enabled = false;
                            }
                        }
                    }
                }
            };


            foreach (ToolStripMenuItem item in this.menu.Items) {
                if (item.DropDownItems.Count > 0) {
                    action.Invoke(item);
                }
            }
        }

        #endregion

        private void FrmMDIContainer_Load(object sender, EventArgs e) {
            this._configProcessor = new ConfigurationProcessor();
            this._alertCount = int.Parse(this._configProcessor.FetchConfigurationByKeyCode("AutoCloseTimes").KeyValue);
            this.timerCheck.Interval = int.Parse(this._configProcessor.FetchConfigurationByKeyCode("Interval").KeyValue) * 1000;
            this.timerCheck.Start();

            this.ExitApplicaton = true;
            this.tssLabelLogin.Text = LoginUserName;
            this.tssLabelCompany.Text = ConfigurationManager.AppSettings["Company"];
            this.tssLabelInfomation.Text = "准备";

            this.SetAllMenuItemPermission();
        }

        private void MenuItem_Click(object sender, EventArgs e) {
            ToolStripMenuItem mi = sender as ToolStripMenuItem;

            #region Miscellaneous items

            switch (mi.Name) {
                case "menuItemAbout":
                    new FrmAbout().ShowDialog();
                    return;
                case "menuItemLogoff":
                    this.ExitApplicaton = false;
                    this.Close();
                    new FrmLogin().Show();
                    return;
                case "AMM1104":
                    new FrmConfig().ShowDialog();
                    return;
            }

            #endregion

            #region Main items

            Form frm = null;
            switch (mi.Name) {
                // 系统设置
                case "AMM1101": frm = new FrmUser(); break;
                case "AMM1102": frm = new FrmRole(); break;
                case "AMM1103": frm = new FrmBasics(); break;
                // 业务管理
                case "AMM1201": frm = new FrmCustomer(); break;
                case "AMM1203": frm = new FrmCustomerOrder(); break;
                case "AMM1202": frm = new FrmPriceEvaluate(); break;
                case "AMM1204": frm = new FrmProduceConduct(); break;
                // 工程管理
                case "AMM1301": frm = new FrmMaterial(); break;
                case "AMM1302": frm = new FrmProduct(); break;
                case "AMM1303": frm = new FrmBOM(); break;
                case "AMM1311": frm = new FrmMould(); break;
                case "AMM1313": frm = new FrmMouldShift(); break;
                // 物控管理
                case "AMM1401": frm = new FrmVendor(); break;
                case "AMM1415": frm = new FrmStoreBasis(); break;
                case "AMM1402": frm = new FrmQuotation(); break;
                case "AMM1404": frm = new FrmOutsourceQuotation(); break;
                case "AMM1403": frm = new FrmProcurementOrder(); break;
                case "AMM1406": frm = new FrmOutsourceOrder(); break;
                case "AMM1416": frm = new FrmSuspenseOrder(); break;
                case "AMM1405": frm = new FrmGenerateProcurementOrder(); break;
                case "AMM1412": frm = new FrmInStoreOrder(); break;
                case "AMM1413": frm = new FrmOutStoreOrder(); break;
                case "AMM1417": frm = new FrmProductInStoreOrder(); break;
                case "AMM1418": frm = new FrmProductOutStoreOrder(); break;
                case "AMM1414": frm = new FrmMaterialInventory(); break;
                case "AMM1419": frm = new FrmProductInventory(); break;
                // 质量管理
                case "AMM1602": frm = new FrmQualityOrder(); break;
                // 生产计划
                case "AMM1501": frm = new FrmProduce(); break;
                case "AMM1502": frm = new FrmProducePlan(); break;
                // 财务管理
                case "AMM1701": frm = new FrmBankAccount(); break;
                case "AMM1702": frm = new FrmCost(); break;
                case "AMM1703": frm = new FrmStatement(); break;
            }
            if (frm != null) {
                frm = this.CheckIfExists(frm);
                frm.Text = mi.Text;
                frm.MdiParent = this;
                //frm.Show();
                //frm.Activate();
                FrmEntry.LoadAndRun(frm);
            }

            #endregion

            #region Report items

            FrmReport frmReport = null;
            switch (mi.Name) {
                case "AMM1801":
                    frmReport = new FrmReport();
                    frmReport.FunctionCode = "AMM1801";
                    frmReport.ReportSearchControl = new MaterialStoreReportSearchControl();
                    break;
                case "AMM1802":
                    frmReport = new FrmReport();
                    frmReport.FunctionCode = "AMM1802";
                    frmReport.ReportSearchControl = new ProductStoreReportSearchControl();
                    break;
                case "AMM1803":
                    frmReport = new FrmReport();
                    frmReport.FunctionCode = "AMM1803";
                    frmReport.ReportSearchControl = new RequirementAnalysisReportSearchControl();
                    break;
                case "AMM1804":
                    frmReport = new FrmReport();
                    frmReport.FunctionCode = "AMM1804";
                    frmReport.ReportSearchControl = new SuspenseUnQualifiedReportSearchControl();
                    break;
                case "AMM1805":
                    frmReport = new FrmReport();
                    frmReport.FunctionCode = "AMM1805";
                    frmReport.ReportSearchControl = new BOMCostReportSearchControl();
                    break;
                case "AMM1806":
                    frmReport = new FrmReport();
                    frmReport.FunctionCode = "AMM1806";
                    frmReport.ReportSearchControl = new ProduceConductCostReportSearchControl();
                    break;
            }
            if (frmReport != null) {
                frmReport = this.CheckIfExists(frmReport);
                frmReport.Name = frmReport.FunctionCode;
                frmReport.Text = mi.Text;
                frmReport.MdiParent = this;
                //frmReport.Show();
                //frmReport.Activate();
                FrmEntry.LoadAndRun(frmReport);
            }

            #endregion
        }

        private void FrmMDIContainer_FormClosing(object sender, FormClosingEventArgs e) {
            if (this.MdiChildren.Count() > 0) {
                e.Cancel = this.ShowQuestion("确定关掉所有子窗体吗？") == DialogResult.No;
            }
        }

        private void tsMenuWindow_DropDownOpening(object sender, EventArgs e) {
            this.tsMenuWindow.DropDownItems.Clear();
            if (this.MdiChildren.Count() > 0) {
                ToolStripMenuItem closeMenuItem = new ToolStripMenuItem();
                closeMenuItem.Text = "关闭所有有窗口";
                closeMenuItem.Click += new EventHandler((s, ea) => {
                    if (this.ShowQuestion("确定关掉所有子窗体吗？") == DialogResult.Yes) {
                        this.MdiChildren.ToList().ForEach(x => { x.Close(); });
                    }
                });
                this.tsMenuWindow.DropDownItems.Add(closeMenuItem);
                this.tsMenuWindow.DropDownItems.Add(new ToolStripSeparator());
            }
            int i = 1;
            this.MdiChildren.ToList().ForEach(x => {
                ToolStripMenuItem windowItem = new ToolStripMenuItem();
                windowItem.Name = x.Name;
                windowItem.Text = string.Format("{0}. {1}", i++, x.Text);
                windowItem.Click += (sender1, e1) => { x.Activate(); };
                if (this.ActiveMdiChild.Name == x.Name) {
                    windowItem.Image = Resources._25_11_;
                }
                this.tsMenuWindow.DropDownItems.Add(windowItem);
            });
        }

        private void msContainer_ItemClicked(object sender, ToolStripItemClickedEventArgs e) {
            switch (e.ClickedItem.Name) {
                case "tsMenuCascade": this.LayoutMdi(MdiLayout.Cascade); break;
                case "tsMenuTileHorizontal": this.LayoutMdi(MdiLayout.TileHorizontal); break;
                case "tsMenuTileVertical": this.LayoutMdi(MdiLayout.TileVertical); break;
                case "tsMenuArrangeIcons": this.LayoutMdi(MdiLayout.ArrangeIcons); break;
            }
        }

        private void timerCheck_Tick(object sender, EventArgs e) {
            if (IsSystem) { return; }
            bool offlineFlag = bool.Parse(this._configProcessor.FetchConfigurationByKeyCode("Offline").KeyValue);
            bool upgradeFlag = bool.Parse(this._configProcessor.FetchConfigurationByKeyCode("Upgrade").KeyValue);

            if (offlineFlag != IsOffline) {
                this.ShowInfo(
                    string.Format("系统管理人员已尝试{1}锁定系统，请尽快保存退出！\r\n\r\n系统将在 {0} 秒后自动关闭！",
                    this._alertCount-- * (this.timerCheck.Interval / 1000),
                    offlineFlag ? string.Empty : "解除"));
            }
            if (upgradeFlag) {
                this.ShowInfo("系统已经有更新版本，请尽快与管理人员联系更新！");
            }

            if (this._alertCount == 0) {
                this.ExitApplicaton = true;
                this.Close();
            }
        }
    }
}
